#!/usr/bin/env python
import sys
sys.path.append("/work/opt/analytic/my_python/lib")
from lib.format_time import *
from lib.HandleMysql import *
from lib.switch_code import *
from lib.load_data import *
from jpype import *
import glob
import re
import os
reload(sys)
sys.setdefaultencoding('utf-8')

class CMCSService(object):
    def __init__(self):
        self.jars = ':'.join(glob.glob('/work/opt/analytic/my_python/java_lib/cmcs/*.jar'))
        self.jvm_path = '/opt/soft/java/jre/lib/amd64/server/libjvm.so'
        startJVM(self.jvm_path,"-ea","-Djava.class.path=%s" % self.jars)
        self.SCFInit =JClass("com.bj58.spat.scf.client.SCFInit")
        self.SCFInit.init('/work/opt/analytic/my_python/java_lib/cmcs/sfb.config')
        
        self.cmcs_class =JClass("com.bj58.sfb.contract.bll.CMCSBLL")
        self.cmcs_bll = self.cmcs_class('cmcs')
        print "ok"
        
        
    def get_param(self,cate_id):
        #print self.query
        self.params = self.cmcs_bll.GetPropertyValue_Post(cate_id,1)
        #rint self.query
        return self.params
    

    def get_cmcs(self,key,cate_id,param_id):
        #print self.query
        self.pv_list =[]
        self.cmcs = self.cmcs_bll.GetListPart(key,cate_id,1,param_id,0,0)
        #rint self.query
        return self.cmcs    
  
    
    def get_cmcs_t(self,list_name,cate_id):

        self.cmcs = self.cmcs_bll.GetProperties(False, list_name,None, "", cate_id, 1, 0, 0, 0, 0, 0);
        
        #rint self.query
        return self.cmcs
    
    def shut_down(self):
        shutdownJVM()

#mysql - dict
def set_dict_conn():    
    conn = HandleMysql('10.5.20.16','58885','ec_stat','L#c8UM5RGh5C','dbwww58com_base_dicts')
    conn.connect()
    return conn

#logic
def execute(s58,date):

    conn = set_dict_conn()
    line_list = []
    stat_table = "t_cmcs_param"
    
    q = "select cateid,dirname from t_category where pid>0"
    cates = conn.get_results(q)
    for cate in cates:
        cate_id = cate[0]
        list_name = cate[1]
        items = s58.get_cmcs_t(list_name,cate_id)
        if items != None and items.allProperties != None:        
            for item in items.allProperties:
                p_name_id = item.getNameId()
                p_param_name = item.getParameterName()
                p_name = item.getName()
                
                param = [p_name_id,p_param_name,p_name,cate_id,0,0,'']
                line_list.append('\t'.join(map(lambda i : str(i), param)))
                
                pvs = item.getPropertyValues()
                if pvs == None or len(pvs)== 0:
                    continue
                
                for pv in pvs:
                    pv_name_id = item.getNameId()
                    pv_val = pv.getValue()
                    pv_txt = pv.getText()
                    pv_vid = pv.getValueId()
                    pv_list_name = pv.getListname()
                    # pv_vid
                    if pv_list_name == None:
                        pv_list_name = ''
                    
                    param = [p_name_id,pv_val,pv_txt,cate_id,1,pv_vid,pv_list_name]
                    line_list.append('\t'.join(map(lambda i : str(i), param)))
                
        items = s58.get_param(cate_id)
        if items != None and len(items)>0:        
            for item in items:
                p_name_id = item.getNameId()
                p_param_name = item.getParameterName()
                p_name = item.getName()
                
                param = [p_name_id,p_param_name,p_name,cate_id,0,0,'']
                line_list.append('\t'.join(map(lambda i : str(i), param)))
                
                pvs = item.getPropertyValues()
                if pvs == None or len(pvs)== 0:
                    continue
                
                for pv in pvs:
                    pv_name_id = item.getNameId()
                    pv_val = pv.getValue()
                    pv_txt = pv.getText()
                    pv_vid = pv.getValueId()
                    pv_list_name = pv.getListname()
                    # pv_vid
                    if pv_list_name == None:
                        pv_list_name = ''
                    
                    param = [p_name_id,pv_val,pv_txt,cate_id,1,pv_vid,pv_list_name]
                    line_list.append('\t'.join(map(lambda i : str(i), param)))
    
    cont = '\n'.join(line_list)
    cont += '\n'
    path = "/work3/opt/analytic/lh_tmp_data/cmcs/"
    file_name = "cmcs_params_%s.txt"%date.replace('-',"")
    writeTextToFile(path,file_name,"w",cont)
    
    q = "truncate table t_cmcs_param"
    conn.execute_sql(q)
    load_data(conn,path+file_name,stat_table,'\t')    
    
def get_ershouche_param(s58,date):
    
    
    conn = set_dict_conn()
    line_list = []
    stat_table = "t_cmcs_param"
    cate_id=29
    
    param = [5867,'chexi','chexi',cate_id,1,0,'']
    line_list.append('\t'.join(map(lambda i : str(i), param)))
    param = [5868,'chexibieming','chexing',cate_id,1,0,'']
    line_list.append('\t'.join(map(lambda i : str(i), param)))
      
    #che leixing
    q = "SELECT list_name FROM `t_cmcs_param`  where param_id=2539 and cate_id=29 and param_type =1"
    cates = conn.get_results(q)
    for cate in cates:
        list_name = cate[0]
        items = s58.get_cmcs_t(list_name,cate_id)
        if items != None and items.allProperties != None:           
            for item in items.allProperties:
                if item.getParameterName() == "brand":
                    pvs = item.getPropertyValues()
                    if pvs == None or len(pvs)== 0:
                        continue
                    
                    for pv in pvs:
                        pv_name_id = item.getNameId()
                        pv_val = pv.getValue()
                        pv_txt = pv.getText()
                        pv_vid = pv.getValueId()
                        pv_list_name = pv.getListname()
                        # pv_vid
                        if pv_list_name == None:
                            pv_list_name = ''
                        
                        param = [pv_name_id,pv_val,pv_txt,cate_id,1,pv_vid,pv_list_name]
                        line_list.append('\t'.join(map(lambda i : str(i), param)))
                        
                        #che xielie
                        chexis = s58.get_cmcs_t(pv_list_name,cate_id)
                        if chexis == None or chexis.allProperties == None:
                            #print pv_list_name
                            continue
                        #print pv_list_name
                        for cx in chexis.allProperties:
                            #print pv_list_name,cx.getParameterName()
                            if cx.getParameterName() == "chexi":
                                cxs = cx.getPropertyValues()
                                if cxs == None or len(cxs)== 0:
                                    continue
                                for c in cxs:
                                    c_name_id = item.getNameId()
                                    c_val = c.getValue()
                                    c_txt = c.getText()
                                    c_vid = c.getValueId()
                                    c_list_name = c.getListname()
                                    # pv_vid
                                    if c_list_name == None:
                                        c_list_name = ''
                                    
                                    #print pv_list_name
                                    param = [c_name_id,c_val,c_txt,5867,1,c_vid,c_list_name]
                                    #print pv_list_name,param
                                    line_list.append('\t'.join(map(lambda i : str(i), param)))
                        
                                    #che xinghao
                                    #print c_list_name
                                    key = "%s_%s"%(c_txt,c_vid)
                                    chexings = s58.get_cmcs(key,cate_id,5867)
                                    for xh in chexings:
                                        #print xh
                                        #print xh.cateName,xh.childPropertys,xh.allProperties
                                        if xh == None or xh.childPropertys == None:
                                            continue
                                        
                                        for cx in xh.childPropertys:
                                           # print cx.getParameterName()
                                            if cx.getParameterName() == "carchexing":
                                                cxs = cx.getPropertyValues()
                                                if cxs == None or len(cxs)== 0:
                                                    continue
                                                for c in cxs:
                                                    cx_name_id = item.getNameId()
                                                    cx_val = c.getValue()
                                                    cx_txt = c.getText()
                                                    cx_vid = c.getValueId()
                                                    cx_list_name = c.getListname()
                                                    # pv_vid
                                                    if cx_list_name == None:
                                                        cx_list_name = ''
                                                    
                                                    param = [cx_name_id,cx_val,cx_txt,5868,1,cx_vid,cx_list_name]
                                                    line_list.append('\t'.join(map(lambda i : str(i), param)))  
    cont = '\n'.join(line_list)
    cont += '\n'
    path = "/work3/opt/analytic/lh_tmp_data/cmcs/"
    file_name = "cmcs_params_che%s.txt"%date.replace('-',"")
    writeTextToFile(path,file_name,"w",cont)
    
    #q = "truncate table t_cmcs_param"
    #conn.execute_sql(q)
    load_data(conn,path+file_name,stat_table,'\t')    


def main():
 
   if len(sys.argv)==1:
        start_date=get_yesterday()
        end_date=start_date
   elif len(sys.argv)==2:
        start_date=format_date(sys.argv[1])
        end_date=start_date
   elif len(sys.argv)==3:
        start_date=format_date(sys.argv[1])
        end_date=format_date(sys.argv[2])
   stat_date=start_date
   s58=CMCSService()
   while stat_date>=start_date and stat_date<=end_date:
        print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
        #
        execute(s58, stat_date) 
        #get_ershouche_param(s58,stat_date)
        
        print "The program of the date of %s is end at %s " %(stat_date,get_now())
        stat_date=var_date(stat_date)

if __name__=='__main__':
    main()
    
    conn = set_dict_conn()
    #q = "truncate table t_cmcs_param"
    #conn.execute_sql(q)
    
    path = "/work3/opt/analytic/lh_tmp_data/cmcs/"
    file_name = "cmcs_params_che20130506.txt"
    load_data(conn,path+file_name,"t_cmcs_param",'\t')
    conn.close()